using Microsoft.AspNetCore.Mvc;
using community.Models;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using community.Data;
using System.Security.Claims;

namespace community.Controllers
{
    /// <summary>
    /// 物业费查询参数
    /// </summary>
    public class PropertyFeeQueryDTO
    {
        /// <summary>
        /// 房屋ID
        /// </summary>
        public int? HouseId { get; set; }

        /// <summary>
        /// 是否已缴费
        /// </summary>
        public bool? IsPaid { get; set; }

        /// <summary>
        /// 到期日期起始时间
        /// </summary>
        public DateTime? DueDateStart { get; set; }

        /// <summary>
        /// 到期日期结束时间
        /// </summary>
        public DateTime? DueDateEnd { get; set; }

        /// <summary>
        /// 每页显示数量，默认10条
        /// </summary>
        [Range(1, 100)]
        public int PageSize { get; set; } = 10;

        /// <summary>
        /// 当前页码，默认第1页
        /// </summary>
        [Range(1, int.MaxValue)]
        public int PageNumber { get; set; } = 1;
    }

    /// <summary>
    /// 创建/更新物业费的数据模型
    /// </summary>
    public class PropertyFeeDTO
    {
        /// <summary>
        /// 房屋ID
        /// </summary>
        [Required(ErrorMessage = "房屋ID不能为空")]
        public int HouseId { get; set; }

        /// <summary>
        /// 费用金额
        /// </summary>
        [Required(ErrorMessage = "费用金额不能为空")]
        [Range(0.01, double.MaxValue, ErrorMessage = "费用金额必须大于0")]
        public double Amount { get; set; }

        /// <summary>
        /// 到期日期
        /// </summary>
        [Required(ErrorMessage = "到期日期不能为空")]
        public DateTime DueDate { get; set; }
    }

    /// <summary>
    /// 缴费状态更新模型
    /// </summary>
    public class PaymentStatusDTO
    {
        /// <summary>
        /// 是否已缴费
        /// </summary>
        [Required(ErrorMessage = "缴费状态不能为空")]
        public bool IsPaid { get; set; }

        /// <summary>
        /// 备注信息
        /// </summary>
        public string? Remark { get; set; }
    }

    /// <summary>
    /// 物业费列表项DTO
    /// </summary>
    public class PropertyFeeListItemDTO
    {
        /// <summary>
        /// 物业费ID
        /// </summary>
        public int Id { get; set; }

        /// <summary>
        /// 房屋ID
        /// </summary>
        public int HouseId { get; set; }

        /// <summary>
        /// 费用金额
        /// </summary>
        public double Amount { get; set; }

        /// <summary>
        /// 是否已缴费
        /// </summary>
        public bool IsPaid { get; set; }



        /// <summary>
        /// 到期日期
        /// </summary>
        public DateTime DueDate { get; set; }

 

        /// <summary>
        /// 楼栋号
        /// </summary>
        public string BuildingNo { get; set; } = string.Empty;

        /// <summary>
        /// 单元号
        /// </summary>
        public string UnitNo { get; set; } = string.Empty;

        /// <summary>
        /// 房间号
        /// </summary>
        public string RoomNo { get; set; } = string.Empty;

        /// <summary>
        /// 业主姓名
        /// </summary>
        public string OwnerName { get; set; } = string.Empty;

        /// <summary>
        /// 业主电话
        /// </summary>
        public string OwnerPhone { get; set; } = string.Empty;
    }

    /// <summary>
    /// 物业费管理接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class PropertyFeeController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public PropertyFeeController(ApplicationDbContext context)
        {
            _context = context;
        }

        private bool IsCurrentUserAdmin()
        {
            var roleClaim = User.FindFirst(ClaimTypes.Role);
            return roleClaim?.Value == "Admin";
        }

        // 获取当前用户ID
        private int GetCurrentUserId()
        {
            var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
            if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out int userId))
            {
                throw new UnauthorizedAccessException("无法获取当前用户ID");
            }
            return userId;
        }

        /// <summary>
        /// 获取物业费列表（支持分页和条件筛选）
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>物业费列表和总数</returns>
        /// <response code="200">成功获取物业费列表</response>
        /// <response code="400">查询参数验证失败</response>
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> GetPropertyFees([FromQuery] PropertyFeeQueryDTO query)
        {
            var fees = _context.PropertyFees
                .Include(f => f.House)
                    .ThenInclude(h => h.Owner)
                .AsQueryable();

            if (query.HouseId.HasValue)
                fees = fees.Where(f => f.HouseId == query.HouseId);

            if (query.IsPaid.HasValue)
                fees = fees.Where(f => f.IsPaid == query.IsPaid);

            if (query.DueDateStart.HasValue)
                fees = fees.Where(f => f.DueDate >= query.DueDateStart);

            if (query.DueDateEnd.HasValue)
                fees = fees.Where(f => f.DueDate <= query.DueDateEnd);
            if (!IsCurrentUserAdmin())
            {
                var userId = GetCurrentUserId();
                // 查询居民表的房子
                var record = _context.Residents.FirstOrDefault(f => f.Id == userId);

                if(record != null)
                {
                    var houseId = record.HouseId;
                    if (houseId != null)
                    {
                        fees = fees.Where(f => f.HouseId == houseId);
                    }
                    else
                    {
                        fees = fees.Where(f => f.HouseId == null);
                    }
                }
                else
                {
                    fees =  fees.Where(f => f.HouseId == null);
                }
            }

            var total = await fees.CountAsync();

            var pagedFees = await fees
                .Skip((query.PageNumber - 1) * query.PageSize)
                .Take(query.PageSize)
                .Select(f => new PropertyFeeListItemDTO
                {
                    Id = f.Id,
                    HouseId = f.HouseId,
                    Amount = f.Amount,
                    IsPaid = f.IsPaid,
                  
                    DueDate = f.DueDate,
                 
                    BuildingNo = f.House.BuildingNo,
                    UnitNo = f.House.UnitNo,
                    RoomNo = f.House.RoomNo,
                    OwnerName = f.House.Owner.Name,
                    OwnerPhone = f.House.Owner.Phone
                })
                .ToListAsync();

            return Ok(new {
                Total = total,
                Items = pagedFees
            });
        }

        /// <summary>
        /// 获取指定物业费详情
        /// </summary>
        /// <param name="id">物业费ID</param>
        /// <returns>物业费详细信息</returns>
        /// <response code="200">成功获取物业费信息</response>
        /// <response code="404">指定ID的物业费不存在</response>
        [HttpGet("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> GetPropertyFee(int id)
        {
            var fee = await _context.PropertyFees.FindAsync(id);
            if (fee == null)
                return NotFound();

            return Ok(fee);
        }

        /// <summary>
        /// 创建物业费记录
        /// </summary>
        /// <param name="dto">物业费信息</param>
        /// <returns>新创建的物业费记录</returns>
        /// <response code="201">成功创建物业费记录</response>
        /// <response code="400">提供的数据无效</response>
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> CreatePropertyFee(PropertyFeeDTO dto)
        {
            var fee = new PropertyFee
            {
                HouseId = dto.HouseId,
                Amount = dto.Amount,
                DueDate = dto.DueDate,
                IsPaid = false,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            _context.PropertyFees.Add(fee);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetPropertyFee), new { id = fee.Id }, fee);
        }

        /// <summary>
        /// 更新物业费信息
        /// </summary>
        /// <param name="id">物业费ID</param>
        /// <param name="dto">更新的物业费信息</param>
        /// <returns>更新后的物业费信息</returns>
        /// <response code="200">成功更新物业费信息</response>
        /// <response code="400">提供的数据无效</response>
        /// <response code="404">指定ID的物业费不存在</response>
        [HttpPut("{id}")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> UpdatePropertyFee(int id, PropertyFeeDTO dto)
        {
            var fee = await _context.PropertyFees.FindAsync(id);
            if (fee == null)
                return NotFound();

            fee.HouseId = dto.HouseId;
            fee.Amount = dto.Amount;
            fee.DueDate = dto.DueDate;
            fee.UpdatedAt = DateTime.UtcNow;

            await _context.SaveChangesAsync();
            return Ok(fee);
        }

        /// <summary>
        /// 更新缴费状态
        /// </summary>
        /// <param name="id">物业费ID</param>
        /// <param name="dto">缴费状态信息</param>
        /// <returns>更新后的物业费信息</returns>
        /// <response code="200">成功更新缴费状态</response>
        /// <response code="400">提供的数据无效</response>
        /// <response code="404">指定ID的物业费不存在</response>
        [HttpPatch("{id}/payment-status")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> UpdatePaymentStatus(int id, PaymentStatusDTO dto)
        {
            var fee = await _context.PropertyFees.FindAsync(id);
            if (fee == null)
                return NotFound();

            fee.IsPaid = dto.IsPaid;
            fee.UpdatedAt = DateTime.UtcNow;

            await _context.SaveChangesAsync();
            return Ok(fee);
        }

        /// <summary>
        /// 删除物业费记录
        /// </summary>
        /// <param name="id">物业费ID</param>
        /// <returns>无内容</returns>
        /// <response code="204">成功删除物业费记录</response>
        /// <response code="404">指定ID的物业费不存在</response>
        [HttpDelete("{id}")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        public async Task<IActionResult> DeletePropertyFee(int id)
        {
            var fee = await _context.PropertyFees.FindAsync(id);
            if (fee == null)
                return NotFound();

            _context.PropertyFees.Remove(fee);
            await _context.SaveChangesAsync();

            return NoContent();
        }
    }
} 